<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>📰 新闻中心 - 股票选股系统</title>
    
    <!-- CSS样式 -->
    <link rel="stylesheet" href="/static/base.css">
    <link rel="stylesheet" href="/static/components.css">
    <link rel="stylesheet" href="/static/pages.css">
    <link rel="stylesheet" href="/static/utilities.css">
    <link rel="stylesheet" href="/static/css/common.css">
    <link href="/static/lib/css/all.min.css" rel="stylesheet">
    <style>
        .news-item {
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            background: white;
            transition: all 0.2s ease;
        }
        
        .news-item:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .news-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }
        
        .news-title {
            flex: 1;
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            cursor: pointer;
            line-height: 1.4;
        }
        
        .news-title:hover {
            color: #3498db;
        }
        
        .news-category-badge {
            margin-left: 12px;
        }
        
        .category-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            text-transform: uppercase;
        }
        
        .category-badge.performance {
            background: #e8f5e8;
            color: #27ae60;
        }
        
        .category-badge.restructure {
            background: #fff3cd;
            color: #f39c12;
        }
        
        .news-content {
            margin-bottom: 12px;
        }
        
        .news-summary {
            color: #555;
            line-height: 1.6;
        }
        
        .news-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            margin-bottom: 12px;
            font-size: 13px;
            color: #666;
        }
        
        .meta-item {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .news-actions {
            display: flex;
            gap: 8px;
        }
        
        .action-btn {
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
            color: #666;
            text-decoration: none;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }
        
        .action-btn:hover {
            background: #f8f9fa;
            border-color: #3498db;
            color: #3498db;
        }
        
        .search-panel {
            display: flex;
            gap: 12px;
            margin-bottom: 16px;
            flex-wrap: wrap;
            align-items: center;
            background: #f8f9fa;
            padding: 16px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }
        
        .search-input-group {
            position: relative;
            flex: 1;
            min-width: 300px;
        }
        
        .search-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
            z-index: 2;
        }
        
        .search-input-group input {
            width: 100%;
            padding: 12px 40px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            box-sizing: border-box;
        }
        
        .search-input-group input:focus {
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }
        
        .clear-search-btn {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #999;
            cursor: pointer;
            padding: 4px;
            border-radius: 50%;
            transition: all 0.2s ease;
        }
        
        .clear-search-btn:hover {
            background: #f0f0f0;
            color: #666;
        }
        
        .search-actions {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        
        .search-status {
            margin-left: 12px;
            font-size: 13px;
            color: #666;
            min-width: 120px;
        }
        
        .search-status.loading {
            color: #3498db;
        }
        
        .search-status.success {
            color: #27ae60;
        }
        
        .search-status.error {
            color: #e74c3c;
        }
        
        .filters {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            flex-wrap: wrap;
            background: white;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
            min-width: 150px;
        }
        
        .category-tabs {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .tab-btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 14px;
            font-weight: 500;
        }
        
        .tab-btn.active {
            background: #3498db;
            color: white;
            border-color: #3498db;
            box-shadow: 0 2px 4px rgba(52, 152, 219, 0.2);
        }
        
        .tab-btn:hover:not(.active) {
            background: #f8f9fa;
            border-color: #3498db;
        }
        
        /* 表单标签样式 */
        .form-label {
            font-weight: 600;
            color: #2c3e50;
            font-size: 14px;
            margin-bottom: 4px;
        }
        
        /* 下拉框样式 */
        .form-select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            background: white;
            font-size: 14px;
            transition: all 0.2s ease;
        }
        
        .form-select:focus {
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
            outline: none;
        }
        
        /* 按钮样式优化 */
        .btn {
            padding: 10px 16px;
            border-radius: 6px;
            font-weight: 500;
            font-size: 14px;
            transition: all 0.2s ease;
            border: 1px solid transparent;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
            border-color: #3498db;
        }
        
        .btn-primary:hover {
            background: #2980b9;
            border-color: #2980b9;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(52, 152, 219, 0.2);
        }
        
        .btn-secondary {
            background: white;
            color: #666;
            border-color: #ddd;
        }
        
                 .btn-secondary:hover {
             background: #f8f9fa;
             border-color: #3498db;
             color: #3498db;
         }
         
         /* 股票价格样式 */
         .stock-price {
             background: #f8f9fa;
             padding: 4px 8px;
             border-radius: 4px;
             border: 1px solid #e9ecef;
         }
         
         .price-value {
             font-weight: 600;
             color: #2c3e50;
             margin-right: 8px;
         }
         
         .change-percent {
             font-weight: 600;
             font-size: 12px;
             padding: 2px 6px;
             border-radius: 3px;
         }
         
         .change-percent.positive {
             background: #f8d7da;
             color: #721c24;
         }
         
         .change-percent.negative {
             background: #d4edda;
             color: #155724;
         }
         
         /* 新闻详情中的股票价格信息 */
         .stock-price-detail {
             background: #f8f9fa;
             border: 1px solid #e9ecef;
             border-radius: 8px;
             padding: 16px;
             margin: 16px 0;
         }
         
         .stock-price-detail h4 {
             margin: 0 0 12px 0;
             color: #2c3e50;
             font-size: 16px;
         }
         
         .price-grid {
             display: grid;
             grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
             gap: 12px;
         }
         
         .price-item {
             display: flex;
             flex-direction: column;
             align-items: center;
             padding: 8px;
             background: white;
             border-radius: 6px;
             border: 1px solid #e9ecef;
         }
         
         .price-label {
             font-size: 12px;
             color: #666;
             margin-bottom: 4px;
         }
         
         .price-value-detail {
             font-weight: 600;
             color: #2c3e50;
         }
     </style>
</head>
<body>
    <div class="app-container">
        <!-- 头部 -->
        <div class="header">
            <div class="header-nav">
                <h1><i class="fas fa-newspaper"></i> 新闻中心</h1>
                <div class="header-nav-links">
                    <!-- 导航将由JavaScript动态生成 -->
                </div>
            </div>
            <p>实时获取A股市场重要新闻，包括业绩预告、资产重组等关键信息，帮助您及时了解市场动态</p>
            <div class="header-stats">
                <div class="stat-item">
                    <div class="stat-number" id="totalNewsCount">-</div>
                    <div class="stat-label">总新闻数量</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="todayNewsCount">-</div>
                    <div class="stat-label">今日新闻</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="lastCrawlTime">-</div>
                    <div class="stat-label">最后更新</div>
                </div>
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content">
              
                 
                    <div class="results-content">
                        <!-- 搜索和过滤器 -->
                        <div class="search-panel">
                            <div class="search-input-group">
                                <i class="fas fa-search search-icon"></i>
                                <input type="text" id="searchInput" placeholder="搜索标题、内容或代码/名称 (支持空格分词)" class="form-control">
                                <button id="clearSearchBtn" class="clear-search-btn" style="display: none;">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <div class="search-actions">
                                <button id="searchBtn" class="btn btn-primary">
                                    <i class="fas fa-search"></i> 搜索
                                </button>
                                <button id="clearBtn" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> 清除
                                </button>
                                <button id="refreshBtn" class="btn btn-secondary">
                                    <i class="fas fa-sync-alt"></i> 刷新
                                </button>
                                <div class="search-status" id="searchStatus"></div>
                            </div>
                        </div>
                        
                        <div class="filters">
                            <div class="filter-group">
                                <label class="form-label">新闻分类</label>
                                <div class="category-tabs">
                                    <button class="tab-btn active" data-category="">所有分类</button>
                                    <button class="tab-btn" data-category="业绩预告">业绩预告</button>
                                    <button class="tab-btn" data-category="资产重组">资产重组</button>
                                </div>
                            </div>
                            
                            <div class="filter-group">
                                <label for="daysFilter" class="form-label">时间范围</label>
                                <select id="daysFilter" class="form-select form-control">
                                    <option value="1">最近1天</option>
                                    <option value="3">最近3天</option>
                                    <option value="7">最近7天</option>
                                    <option value="30" selected>最近30天</option>
                                    <option value="0">全部时间</option>
                                </select>
                            </div>
                            
                            <div class="filter-group">
                                <label for="limitFilter" class="form-label">显示条数</label>
                                <select id="limitFilter" class="form-select form-control">
                                    <option value="20">显示20条</option>
                                    <option value="50" selected>显示50条</option>
                                    <option value="100">显示100条</option>
                                    <option value="200">显示200条</option>
                                </select>
                            </div>
                        </div>
                        
                        <!-- 新闻列表 -->
                        <div id="newsContainer">
                            <div class="loading" id="loadingIndicator">
                                <div class="spinner"></div>
                                <p>加载中...</p>
                            </div>
                        </div>
                        
                        <!-- 分页控件 -->
                        <div id="pagination" class="pagination-container">
                            <div class="pagination">
                                <button id="prevPage" class="pagination-btn pagination-prev">
                                    <i class="fas fa-chevron-left"></i> 上一页
                                </button>
                                <div class="pagination-pages"></div>
                                <button id="nextPage" class="pagination-btn pagination-next">
                                    下一页 <i class="fas fa-chevron-right"></i>
                                </button>
                            </div>
                            <div class="pagination-info">
                                显示 <span id="currentRange">0-0</span> 条，共 <span id="totalItems">0</span> 条
                            </div>
        </div>
    </div>

    <!-- 新闻详情模态框 -->
    <div id="newsDetailModal" class="news-detail-modal">
        <div class="news-detail-content">
            <span class="close-modal" onclick="closeNewsDetail()">&times;</span>
            <div id="newsDetailContent">
                <!-- 新闻详情内容 -->
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentNews = [];
        let isLoading = false;
        let searchTimeout = null; // 防抖搜索
        
        // 分页相关变量
        let currentPage = 1;
        let itemsPerPage = 50;  // 与limitFilter的默认选中值保持一致
        let totalPages = 1;

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadNewsList();
            bindEvents();
        });

        // 绑定事件
        function bindEvents() {
            // 获取所有需要绑定事件的元素
            const elements = {
                searchBtn: document.getElementById('searchBtn'),
                searchInput: document.getElementById('searchInput'),
                clearSearchBtn: document.getElementById('clearSearchBtn'),
                clearBtn: document.getElementById('clearBtn'),
                refreshBtn: document.getElementById('refreshBtn'),
                daysFilter: document.getElementById('daysFilter'),
                limitFilter: document.getElementById('limitFilter'),
                prevPage: document.getElementById('prevPage'),
                nextPage: document.getElementById('nextPage'),
                newsDetailModal: document.getElementById('newsDetailModal')
            };
            
            // 搜索按钮事件
            if (elements.searchBtn) {
                elements.searchBtn.addEventListener('click', searchNews);
            }
            
            // 搜索输入框事件
            if (elements.searchInput) {
                // Enter键搜索
                elements.searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        searchNews();
                    }
                });
                
                // 输入时显示/隐藏清除按钮和防抖搜索
                elements.searchInput.addEventListener('input', function() {
                    const clearBtn = document.getElementById('clearSearchBtn');
                    if (this.value.trim()) {
                        clearBtn.style.display = 'block';
                        
                        // 防抖搜索：500ms后自动搜索
                        clearTimeout(searchTimeout);
                        searchTimeout = setTimeout(() => {
                            if (this.value.trim()) {
                                searchNews();
                            }
                        }, 500);
                    } else {
                        clearBtn.style.display = 'none';
                        clearTimeout(searchTimeout);
                        loadNewsList();
                    }
                });
                
                // 聚焦时高亮
                elements.searchInput.addEventListener('focus', function() {
                    this.parentElement.style.boxShadow = '0 0 0 3px rgba(52, 152, 219, 0.1)';
                });
                
                elements.searchInput.addEventListener('blur', function() {
                    this.parentElement.style.boxShadow = 'none';
                });
            }
            
            // 清除搜索按钮事件
            if (elements.clearSearchBtn) {
                elements.clearSearchBtn.addEventListener('click', function() {
                    document.getElementById('searchInput').value = '';
                    this.style.display = 'none';
                    loadNewsList();
                    updateSearchStatus('', '');
                });
            }
            
            // 清除所有按钮事件
            if (elements.clearBtn) {
                elements.clearBtn.addEventListener('click', function() {
                    document.getElementById('searchInput').value = '';
                    document.getElementById('clearSearchBtn').style.display = 'none';
                    // 重置所有过滤器
                    document.querySelector('.tab-btn.active').classList.remove('active');
                    document.querySelector('[data-category=""]').classList.add('active');
                    document.getElementById('daysFilter').value = '30';
                    document.getElementById('limitFilter').value = '50';
                    loadNewsList();
                    updateSearchStatus('', '');
                });
            }
            
            // 刷新按钮事件
            if (elements.refreshBtn) {
                elements.refreshBtn.addEventListener('click', function() {
                    this.disabled = true;
                    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 刷新中...';
                    loadNewsList().finally(() => {
                        this.disabled = false;
                        this.innerHTML = '<i class="fas fa-sync-alt"></i> 刷新';
                    });
                });
            }
            

            
            // Tab分类切换 - 直接绑定事件，不需要setTimeout
            const tabButtons = document.querySelectorAll('.tab-btn');
            tabButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // 移除所有按钮的active类
                    tabButtons.forEach(btn => btn.classList.remove('active'));
                    // 为当前按钮添加active类
                    this.classList.add('active');
                    // 重置分页到第一页
                    currentPage = 1;
                    // 加载对应分类的新闻
                    loadNewsList();
                });
            });
            
            // 删除setTimeout代码块
            // setTimeout(function() {
            //     const tabButtons = document.querySelectorAll('.tab-btn');
            //     tabButtons.forEach(button => {
            //         button.addEventListener('click', function() {
            //             // 移除所有按钮的active类
            //             tabButtons.forEach(btn => btn.classList.remove('active'));
            //             // 为当前按钮添加active类
            //             this.classList.add('active');
            //             // 重置分页到第一页
            //             currentPage = 1;
            //             // 加载对应分类的新闻
            //             loadNewsList();
            //         });
            //     });
            // }, 0);
            
            // 过滤器变化
            if (elements.daysFilter) {
                elements.daysFilter.addEventListener('change', loadNewsList);
            }
            
            if (elements.limitFilter) {
                elements.limitFilter.addEventListener('change', function() {
                    itemsPerPage = parseInt(this.value);
                    currentPage = 1;
                    loadNewsList();
                });
            }
            
            // 分页按钮事件
            if (elements.prevPage) {
                elements.prevPage.addEventListener('click', () => goToPage(currentPage - 1));
            }
            
            if (elements.nextPage) {
                elements.nextPage.addEventListener('click', () => goToPage(currentPage + 1));
            }
            
            // 点击模态框背景关闭
            if (elements.newsDetailModal) {
                elements.newsDetailModal.addEventListener('click', function(e) {
                    if (e.target === this) {
                        closeNewsDetail();
                    }
                });
            }
        }

        // 加载新闻列表
        async function loadNewsList() {
            if (isLoading) return;
            
            try {
                isLoading = true;
                showLoading(true);
                
                // 获取当前选中的分类
                const activeTab = document.querySelector('.tab-btn.active');
                const category = activeTab ? activeTab.dataset.category : '';
                
                const daysBack = document.getElementById('daysFilter').value;
                const limit = document.getElementById('limitFilter').value;
                
                const params = new URLSearchParams({
                    limit: limit,
                    days_back: daysBack
                });
                
                if (category) {
                    params.append('category', category);
                }
                
                const response = await fetch(`/api/news/list?${params}`);
                const result = await response.json();
                
                if (result.success) {
                    currentNews = result.data.news_list;
                    currentPage = 1; // 重置到第一页
                    const paginatedNews = currentNews.slice(0, itemsPerPage);
                    displayNewsList(paginatedNews);
                    setupPagination(currentNews);
                    updateStats(currentNews);
                    
                    // 更新搜索状态
                    if (currentNews.length > 0) {
                        updateSearchStatus(`已加载 ${currentNews.length} 条新闻`, 'success');
                    } else {
                        updateSearchStatus('暂无新闻数据', 'error');
                    }
                } else {
                    showError('加载新闻失败：' + result.error);
                    updateSearchStatus('加载失败', 'error');
                }
                
            } catch (error) {
                console.error('加载新闻列表失败:', error);
                showError('加载新闻列表失败：' + error.message);
                updateSearchStatus('加载失败', 'error');
                
                // 确保在错误情况下也隐藏加载指示器
                const loadingIndicator = document.getElementById('loadingIndicator');
                if (loadingIndicator) {
                    loadingIndicator.style.display = 'none';
                }
            } finally {
                isLoading = false;
                showLoading(false);
            }
        }

        // 搜索新闻
        async function searchNews() {
            const input = document.getElementById('searchInput').value.trim();
            if (!input) {
                updateSearchStatus('请输入搜索关键词', 'error');
                return;
            }
            if (isLoading) return;
            
            try {
                isLoading = true;
                showLoading(true);
                updateSearchStatus('搜索中...', 'loading');
                
                const limit = document.getElementById('limitFilter').value;
                const response = await fetch(`/api/news/search?keyword=${encodeURIComponent(input)}&limit=${limit}`);
                const result = await response.json();
                
                if (!result.success) throw new Error(result.error || '搜索失败');
                
                let list = result.data.news_list || [];
                const tokens = input.split(/\s+/).filter(Boolean).map(t => t.toLowerCase());
                
                // 多关键词本地过滤
                if (tokens.length > 1) {
                    list = list.filter(n => {
                        const hay = `${n.title||''} ${n.summary||''} ${n.stock_code||''} ${n.stock_name||''}`.toLowerCase();
                        return tokens.every(t => hay.includes(t));
                    });
                }
                
                currentNews = list;
                currentPage = 1;
                const paginatedNews = currentNews.slice(0, itemsPerPage);
                displayNewsList(paginatedNews);
                setupPagination(currentNews);
                updateStats(currentNews);
                
                // 更新搜索状态
                if (list.length > 0) {
                    updateSearchStatus(`找到 ${list.length} 条结果`, 'success');
                } else {
                    updateSearchStatus('未找到相关结果', 'error');
                }
                
            } catch (error) {
                console.error('搜索新闻失败:', error);
                showError('搜索失败：' + error.message);
                updateSearchStatus('搜索失败', 'error');
            } finally {
                isLoading = false;
                showLoading(false);
            }
        }
        
        // 更新搜索状态
        function updateSearchStatus(message, type) {
            const statusEl = document.getElementById('searchStatus');
            if (!statusEl) return;
            
            statusEl.textContent = message;
            statusEl.className = 'search-status';
            
            if (type) {
                statusEl.classList.add(type);
            }
            
            // 3秒后清除状态信息
            if (message && type !== 'loading') {
                setTimeout(() => {
                    statusEl.textContent = '';
                    statusEl.className = 'search-status';
                }, 3000);
            }
        }

        // 显示新闻列表
        function displayNewsList(newsList) {
            const container = document.getElementById('newsContainer');
            
            if (!newsList || newsList.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-newspaper"></i>
                        <h3>暂无新闻数据</h3>
                        <p>暂无新闻数据，请稍后再试</p>
                    </div>
                `;
                // 隐藏分页控件
                document.getElementById('pagination').style.display = 'none';
                return;
            }
            
            const newsHTML = newsList.map(news => {
                // 构建标题：证券代码、证券名称、公告内容
                let titleText = '';
                let stockInfo = '';
                
                // 构建股票信息部分
                if (news.stock_name && news.stock_code) {
                    stockInfo = `${escapeHtml(news.stock_code)} ${escapeHtml(news.stock_name)}`;
                } else if (news.stock_code) {
                    stockInfo = `${escapeHtml(news.stock_code)}`;
                }
                
                // 构建公告内容部分
                let announcementContent = '';
                if (news.title) {
                    announcementContent = escapeHtml(news.title);
                } else if (news.summary) {
                    // 从摘要中提取前50个字符作为公告内容
                    announcementContent = escapeHtml(news.summary.substring(0, 50));
                    if (news.summary.length > 50) {
                        announcementContent += '...';
                    }
                } else {
                    announcementContent = '未知公告';
                }
                
                // 组合完整标题
                if (stockInfo) {
                    titleText = `${stockInfo} - ${announcementContent}`;
                } else {
                    titleText = announcementContent;
                }
                
                // 构建内容：显示详细摘要
                let contentText = '';
                if (news.summary) {
                    contentText = escapeHtml(news.summary);
                } else if (news.title) {
                    contentText = escapeHtml(news.title);
                } else {
                    contentText = '暂无详细内容';
                }
                
                return `
                    <div class="news-item">
                        <div class="news-header">
                            <div class="news-title" onclick="showNewsDetail('${news.news_id}')">
                                <i class="fas fa-bullhorn"></i> ${titleText}
                            </div>
                            <div class="news-category-badge">
                                ${news.category ? `<span class="category-badge ${news.category === '业绩预告' ? 'performance' : 'restructure'}">${escapeHtml(news.category)}</span>` : ''}
                            </div>
                        </div>
                        <div class="news-content">
                            <div class="news-summary">
                                ${contentText.substring(0, 200)}${contentText.length > 200 ? '...' : ''}
                            </div>
                        </div>
                                                 <div class="news-meta">
                             <span class="meta-item"><i class="far fa-calendar"></i> ${formatDateTime(news.publish_time)}</span>
                             <span class="meta-item"><i class="fas fa-building"></i> ${escapeHtml(news.source || '未知来源')}</span>
                             <span class="meta-item"><i class="fas fa-clock"></i> ${formatDateTime(news.crawl_time)}</span>
                             ${news.stock_price ? `
                                 <span class="meta-item stock-price">
                                     <i class="fas fa-chart-line"></i> 
                                     <span class="price-value">¥${news.stock_price.latest_price}</span>
                                     <span class="change-percent ${news.stock_price.change_percent >= 0 ? 'positive' : 'negative'}">
                                         ${news.stock_price.change_percent >= 0 ? '+' : ''}${news.stock_price.change_percent}%
                                     </span>
                                 </span>
                             ` : ''}
                         </div>
                        <div class="news-actions">
                            ${news.url ? `<a href="${news.url}" target="_blank" class="action-btn"><i class="fas fa-external-link-alt"></i> 原文</a>` : ''}
                            <button onclick="showNewsDetail('${news.news_id}')" class="action-btn">
                                <i class="fas fa-eye"></i> 详情
                            </button>
                        </div>
                    </div>
                `;
            }).join('');
            
            container.innerHTML = newsHTML;
        }

        // 显示新闻详情
        async function showNewsDetail(newsId) {
            try {
                const response = await fetch(`/api/news/detail/${newsId}`);
                const result = await response.json();
                
                if (result.success) {
                    const news = result.data;
                    const detailContent = document.getElementById('newsDetailContent');
                    
                    // 构建股票信息显示
                    let stockInfo = '';
                    if (news.stock_name && news.stock_code) {
                        stockInfo = `
                            <div class="mb-4">
                                <h4><i class="fas fa-chart-line"></i> 股票信息</h4>
                                <div class="alert alert-info">
                                    <strong>证券名称：</strong>${escapeHtml(news.stock_name)}<br>
                                    <strong>证券代码：</strong>${escapeHtml(news.stock_code)}
                                </div>
                            </div>
                        `;
                    }
                    
                                         detailContent.innerHTML = `
                         <h2>${escapeHtml(news.title)}</h2>
                         <div class="news-meta mb-4">
                             <span><i class="far fa-calendar"></i> ${formatDateTime(news.publish_time)}</span>
                             <span><i class="fas fa-building"></i> ${escapeHtml(news.source || '未知来源')}</span>
                             ${news.author ? `<span><i class="fas fa-user"></i> ${escapeHtml(news.author)}</span>` : ''}
                             ${news.category ? `<span><i class="fas fa-tag"></i> ${escapeHtml(news.category)}</span>` : ''}
                         </div>
                         ${stockInfo}
                         ${news.stock_price ? `
                             <div class="stock-price-detail">
                                 <h4><i class="fas fa-chart-line"></i> 股票价格信息</h4>
                                 <div class="price-grid">
                                     <div class="price-item">
                                         <div class="price-label">最新价格</div>
                                         <div class="price-value-detail">¥${news.stock_price.latest_price}</div>
                                     </div>
                                     <div class="price-item">
                                         <div class="price-label">涨跌幅</div>
                                         <div class="price-value-detail ${news.stock_price.change_percent >= 0 ? 'positive' : 'negative'}">
                                             ${news.stock_price.change_percent >= 0 ? '+' : ''}${news.stock_price.change_percent}%
                                         </div>
                                     </div>
                                     <div class="price-item">
                                         <div class="price-label">开盘价</div>
                                         <div class="price-value-detail">¥${news.stock_price.open_price}</div>
                                     </div>
                                     <div class="price-item">
                                         <div class="price-label">最高价</div>
                                         <div class="price-value-detail">¥${news.stock_price.high_price}</div>
                                     </div>
                                     <div class="price-item">
                                         <div class="price-label">最低价</div>
                                         <div class="price-value-detail">¥${news.stock_price.low_price}</div>
                                     </div>
                                     <div class="price-item">
                                         <div class="price-label">成交量</div>
                                         <div class="price-value-detail">${formatVolume(news.stock_price.volume)}</div>
                                     </div>
                                 </div>
                             </div>
                         ` : ''}
                        ${news.summary ? `
                            <div class="mb-4">
                                <h4><i class="fas fa-quote-left"></i> 公告摘要</h4>
                                <p class="news-summary">${escapeHtml(news.summary)}</p>
                            </div>
                        ` : ''}
                        ${(news.category === '业绩预告') ? `
                            <div class="mb-4">
                                <h4><i class="fas fa-chart-bar"></i> 业绩预告详情</h4>
                                <div class="news-content">
                                    <ul>
                                        ${news.forecast_indicator ? `<li><strong>预测指标：</strong>${escapeHtml(news.forecast_indicator)}</li>` : ''}
                                        ${news.forecast_value ? `<li><strong>预测数值：</strong>${escapeHtml(news.forecast_value)}</li>` : ''}
                                        ${news.yoy_change ? `<li><strong>业绩变化(同比)：</strong>${escapeHtml(news.yoy_change)}</li>` : ''}
                                        ${news.qoq_change ? `<li><strong>业绩变化(环比)：</strong>${escapeHtml(news.qoq_change)}</li>` : ''}
                                        ${news.change_reason ? `<li><strong>业绩变动原因：</strong>${escapeHtml(news.change_reason)}</li>` : ''}
                                        ${news.forecast_type ? `<li><strong>预告类型：</strong>${escapeHtml(news.forecast_type)}</li>` : ''}
                                        ${news.last_year_value ? `<li><strong>上年同期值：</strong>${escapeHtml(news.last_year_value)}</li>` : ''}
                                    </ul>
                                </div>
                            </div>
                        ` : (news.content ? `
                            <div class="mb-4">
                                <h4><i class="fas fa-align-left"></i> 详细内容</h4>
                                <div class="news-content">
                                    ${escapeHtml(news.content).replace(/\n/g, '<br>')}
                                </div>
                            </div>
                        ` : '')}
                        ${news.url ? `
                            <div class="mb-3">
                                <a href="${news.url}" target="_blank" class="btn btn-outline-primary">
                                    <i class="fas fa-book-reader"></i> 查看原文
                                </a>
                            </div>
                        ` : ''}
                    `;
                    
                    document.getElementById('newsDetailModal').style.display = 'block';
                } else {
                    alert('获取新闻详情失败：' + result.error);
                }
                
            } catch (error) {
                console.error('获取新闻详情失败:', error);
                alert('获取新闻详情失败：' + error.message);
            }
        }

        // 关闭新闻详情
        function closeNewsDetail() {
            document.getElementById('newsDetailModal').style.display = 'none';
        }

        // 更新统计信息
        function updateStats(newsList) {
            const totalCountEl = document.getElementById('totalNewsCount');
            const todayCountEl = document.getElementById('todayNewsCount');
            const lastCrawlTimeEl = document.getElementById('lastCrawlTime');
            
            // 添加null检查，防止Cannot read properties of null错误
            if (!totalCountEl || !todayCountEl || !lastCrawlTimeEl) return;
            
            const totalCount = newsList.length;
            const today = new Date().toDateString();
            const todayCount = newsList.filter(news => {
                if (!news.publish_time) return false;
                return new Date(news.publish_time).toDateString() === today;
            }).length;
            
            const latestNews = newsList.length > 0 ? newsList[0] : null;
            const lastUpdateTime = latestNews ? formatDateTime(latestNews.crawl_time) : '-';
            
            totalCountEl.textContent = totalCount;
            todayCountEl.textContent = todayCount;
            lastCrawlTimeEl.textContent = lastUpdateTime;
        }

        // 显示/隐藏加载指示器
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const newsContainer = document.getElementById('newsContainer');
            
            // 添加null检查，防止Cannot read properties of null错误
            if (!loadingIndicator) return;
            
            if (show) {
                loadingIndicator.style.display = 'block';
            } else {
                loadingIndicator.style.display = 'none';
            }
        }

        // 显示错误信息
        function showError(message) {
            const container = document.getElementById('newsContainer');
            
            // 添加null检查
            if (!container) {
                console.error('新闻容器元素不存在');
                return;
            }
            
            container.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>错误：</strong> ${escapeHtml(message)}
                </div>
            `;
        }

        // HTML转义
        function escapeHtml(unsafe) {
            if (typeof unsafe !== 'string') return '';
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 分页功能
        function setupPagination(newsList) {
    const totalItemsEl = document.getElementById('totalItems');
    const prevPageBtn = document.getElementById('prevPage');
    const nextPageBtn = document.getElementById('nextPage');
    const pagination = document.getElementById('pagination');
    
    // 添加null检查
    if (!totalItemsEl || !prevPageBtn || !nextPageBtn || !pagination) return;
    
    const totalItems = newsList.length;
    totalPages = Math.ceil(totalItems / itemsPerPage);
    
    // 处理边界情况
    if (totalPages === 0) {
        totalPages = 1;
    }
    
    if (currentPage > totalPages) {
        currentPage = totalPages;
    }
    
    if (currentPage < 1) {
        currentPage = 1;
    }
    
    // 更新分页信息
    totalItemsEl.textContent = totalItems;
    updatePageRange();
    
    // 更新分页按钮状态
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
    
    // 生成页码按钮
    const pagesContainer = document.querySelector('.pagination-pages');
    if (!pagesContainer) return;
    
    pagesContainer.innerHTML = '';
    
    // 显示最多7个页码按钮
    let startPage = Math.max(1, currentPage - 3);
    let endPage = Math.min(totalPages, startPage + 6);
    
    if (endPage - startPage < 6) {
        startPage = Math.max(1, endPage - 6);
    }
    
    // 只有在有数据时才显示页码按钮
    if (totalItems > 0) {
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `page-btn ${i === currentPage ? 'active' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => goToPage(i));
            pagesContainer.appendChild(pageBtn);
        }
    }
    
    // 显示/隐藏分页控件
    pagination.style.display = totalItems > 0 ? 'flex' : 'none';
}

        function updatePageRange() {
    const currentRangeEl = document.getElementById('currentRange');
    const totalItemsEl = document.getElementById('totalItems');
    
    // 添加null检查
    if (!currentRangeEl || !totalItemsEl) return;
    
    const totalItems = parseInt(totalItemsEl.textContent) || 0;
    
    if (totalItems === 0) {
        currentRangeEl.textContent = '0-0';
        return;
    }
    
    const start = (currentPage - 1) * itemsPerPage + 1;
    const end = Math.min(currentPage * itemsPerPage, totalItems);
    currentRangeEl.textContent = `${start}-${end}`;
}

        function goToPage(page) {
            if (page < 1 || page > totalPages) return;
            
            currentPage = page;
            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const paginatedNews = currentNews.slice(startIndex, endIndex);
            
            displayNewsList(paginatedNews);
            setupPagination(currentNews);
            
            // 滚动到顶部
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

                 // 格式化日期时间
         function formatDateTime(dateStr) {
             if (!dateStr) return '-';
             
             try {
                 const date = new Date(dateStr);
                 const year = date.getFullYear();
                 const month = String(date.getMonth() + 1).padStart(2, '0');
                 const day = String(date.getDate()).padStart(2, '0');
                 
                 return `${year}/${month}/${day}`;
             } catch (error) {
                 return dateStr;
             }
         }
         
    </script>
    
    <!-- 公共JavaScript库 -->
    <script src="/static/js/common.js"></script>
    <script src="/static/js/navigation.js"></script>
</body>
</html>